package coder.nav.sdk;

import cn.hutool.crypto.SecureUtil;
import coder.nav.utils.HttpUtils;
import com.alibaba.fastjson2.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 百度-翻译
 * @author Bosen 2024/10/23 11:31
 */
public class BaiduTransAPI {

    private static final String API = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    private static final String APPID = "20241021002181819";
    private static final String SECURITY_KEY = "5Q8iCQTOevm98Sl0y3JW";

    public static String getResult(String query, String from, String to) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("q", query);
            params.put("from", from);
            params.put("to", to);
            params.put("appid", APPID);
            // 随机数
            String salt = String.valueOf(System.currentTimeMillis());
            params.put("salt", salt);
            // 签名
            String src = APPID + query + salt + SECURITY_KEY; // 加密前的原文
            params.put("sign", SecureUtil.md5(src));

            String response = HttpUtils.sendGetRequest(API, params, null);
            JSONObject json = JSONObject.parseObject(response);
            return json.getJSONArray("trans_result").getJSONObject(0).get("dst").toString();
        } catch (Exception ex) {
            return null;
        }
    }

}
